
const dbQuery = require("../model/model.js");
let CryptoJS = require('crypto-js')
let path = require("path")
let fs = require('fs')
let { secret } = require("../config/config.js");
let { getNowDate } = require("../util/tool.js")
let user = {};

//输出一个登录表单页面
user.login = (req, res) => {
    if (req.session.userInfo) {
        res.render("/")
    } else {
        res.render("login.html")
    }
}

//登录1
user.dologin = (req, res) => {
    let { username, password } = req.body;
    // let secret = "!@#$%^&*()-=+_"
    // password = CryptoJS.MD5(`${password}${secret}`).toString()

    let sql = `select * from user_information where account_number = '${username}' and user_password = '${password}'`;


    dbQuery(sql).then(result => {

        if (result.length > 0) {
            let userInfo = result[0];
            req.session.userInfo = JSON.stringify(userInfo);

            let sql2 = `update user_information set last_login_time = '${getNowDate()}' where id = '${userInfo.id}' `
            dbQuery(sql2).catch(err => {
                if (err) { throw err; } //如果错误抛出异常
                // res.redirect('/')
                res.json({ errcode: 11, message: "正确" })
            })

        } else {
            res.json({ errcode: 22, message: "错误" })
            // res.send("<script>alert('用户或密码错误')location.href = '/login'</script>")
        }
    })
}


//登录2
user.ajaxlogin = (req, res) => {
    let { username, password } = req.body;
    // let secret = "!@#$%^&*()-=+_"
    // password = CryptoJS.MD5(`${password}${secret}`).toString()

    let sql = `select * from user_information where account_number = '${username}' and user_password = '${password}'`;


    dbQuery(sql).then(result => {

        if (result.length > 0) {

            let userInfo = result[0];
            req.session.userInfo = JSON.stringify(userInfo);
            let sql2 = `update user_information set last_login_time = '${getNowDate()}' where id = '${userInfo.id}'`
            dbQuery(sql2)
            .then(result => {
                res.json({
                    message: "success",
                    code: 20000
                })
            })
            .catch(err => {
                if (err) { throw err; } //如果错误抛出异常
                // res.redirect('/')

            })


        } else {
            res.json({
                message: "失败",
                code: -1
            })
        }
    })
}


//用户退出逻辑
user.logout = (req, res) => {
    //清除用户数据
    req.session.destroy((err) => {
        if (err) throw err
    })
    res.redirect('/login')
}


//注册账号
user.register = (req, res) => {
    res.render("register.html")
}

//ajaxregister 注册
user.ajaxregister = (req, res) => {
    let { account_number, user_mailbox, user_password, aencode } = req.body//接收传过来的数据

    if ([account_number, user_mailbox, user_password, aencode].includes('')) { // 对应表里的数据
        res.json({
            message: '参数不能为空',
            code: -1
        })
        return;
    }
    if (user_password !== aencode) {
        res.json({
            message: "两次密码不一致",
            code: -2
        })
        return;
    }
    password = CryptoJS.MD5(`${user_password}${secret}`).toString();
    let last_login_time = getNowDate();
    let sql = `insert into user_information(account_number,user_password,user_mailbox,last_login_time)
    value("${account_number}","${user_password}","${user_mailbox}","${last_login_time}")`
    //表里的数据
    dbQuery(sql).then(result => {
        if (result.affectedRows) {
            res.json({
                code: 20000,
                message: 'success'
            })
        } else {
            res.json({
                code: -3,
                message: "服务器正在忙，请稍后再试   ┭┮﹏┭┮"

            })

        }
    })

}

//校验ajaxemail
user.ajaxemail = (req, res) => {
    let { user_mailbox } = req.body;
    let sql = `select * from user_information where user_mailbox = "${user_mailbox}"`;
    dbQuery(sql).then(result => {
        if (result.length > 0) {
            res.json({
                code: -5,
                message: "邮箱以被注册，请您重新注册一个"
            })
        } else {
            res.json({
                code: 20000,
                message: "邮箱可用"
            })
        }
    })
}

//上传头像
user.uploadAvatar = (req, res) => {
    let { originalname, filename, destination } = req.file
    let ext = originalname.substring(originalname.indexOf('.'));
    let oldPath = path.join(__dirname, '../', 'uploads', filename);
    let newPath = path.join(__dirname, '../', 'uploads', filename) + ext;
    fs.renameSync(oldPath, newPath)
    // 把上传成功的图片路径更新到用户表中
    let userInfo = JSON.parse(req.session.userInfo);
    let { id } = userInfo;
    let avatar = 'uploads/' + filename + ext;

    let sql = `update user_information set user_Avatar = '${avatar}' where id = ${id}`

    dbQuery(sql).catch(err => {
        userInfo.user_Avatar = avatar;
        req.session.userInfo = JSON.stringify(userInfo)
        if (err) { throw err; }
        res.json({
            code: 20000,
            message: "上传成功",
            src: avatar
        })
    })

}

//修改密码
user.updatePassword = (req, res) => {

    let { oldpwd, newpwd, renewpwd } = req.body;
    let { id } = JSON.parse(req.session.userInfo)

    let = sql = `select user_password from user_information where id  =${id}`
    dbQuery(sql).then(result => {
        if (result.length) {
            // oldPwd = CryptoJS.MD5(`${oldpwd}${secret}`).toString(); 

            if (result[0].user_password != oldpwd) {
                // console.log(result[0].user_password)
                // console.log(oldPwd)
                res.json({
                    code: -1,
                    message: "旧密码不匹配"
                })
            } else {
                // newpwd = CryptoJS.MD5(`${oldpwd}${secret}`).toString(); 
                let = sql = `update user_information set user_password  = "${newpwd}" where id = ${id}`
                dbQuery(sql).then(result => {
                    // console.log(result)
                    if (result.affectedRows) {
                        res.json({
                            code: 20000,
                            message: '更新密码'
                        })
                    } else {
                        res.josn({
                            code: -2,
                            message: '服务器繁忙，请稍后再试'
                        })
                    }
                })
            }
        }
    })
}

module.exports = user;